package Linked;

import java.util.Iterator;
import java.util.Objects;

public class List implements Iterable<Integer> {

    //定义哨兵
    private final Node hand;

    //节点类
    static class Node {
        public int value;
        public Node next;

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Node node = (Node) o;
            return value == node.value && Objects.equals(next, node.next);
        }

        @Override
        public int hashCode() {
            return Objects.hash(value, next);
        }

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;


        }

    }

    //初始化哨兵节点
    public List() {
        hand = new Node(0,null);
    }


    //重写迭代器
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = hand.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }


    //头插节点
    public void addFirst(int value) {
        hand.next = new Node(value,hand.next);
    }

    //尾插节点
    public void addLast(int value) {
        Node p = hand;
        while (p.next != null) {
            p = p.next;
        }
        p.next = new Node(value,null);
    }


    //删除有重复的节点(重复的值，只保留其中一个)
    // 1、1、2、3、3

    public List removeRepeat(List list) {

        if (list.hand == null || list.hand.next == null) {
            return list;
        }

        Node o1 = list.hand.next;
        Node o2 = list.hand.next.next;
/*        while (o2 != null) {

            while ( o2 != null && o1.value == o2.value) {
                o2 = o2.next;
            }
            if (o2 == null) {
                o1.next = null;
                return list;
            }

            o1.next = o2;
            o1 = o2;
            o2 = o2.next;

        }*/
        while (o2 != null) {
            if (o2.value != o1.value) {
                o1.next = o2;
                o1 = o1.next;
            }
            o2 = o2.next;
        }
        o1.next = null;
        return list;

    }

    //删除有重复的节点(使用递归方法)
    public List removeRepeatRecursion(List list) {
        Node p = list.hand;
        recursion(p);
        return list;
    }

    public Node recursion(Node p) {
        if (p == null || p.next == null) {
            return p;
        }

        if (p.value == p.next.value) {
            return recursion(p.next);
        } else {
            p.next = recursion(p.next);
            return p;
        }

    }

}
